<template>
  <van-nav-bar
    :title="title"
    :left-text="leftText"
    :left-arrow="showLeftArrow"
    @click-left="onClickLeft"
    :right-text="rightText"
    :right-arrow="showRightArrow"
    @click-right="onClickRight"
  >
  </van-nav-bar>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, watch, watchEffect } from "vue";
import { useRouter } from "vue-router";

export default defineComponent({
  name: "NavBar",
  props: {
    title: {
      type: String,
      require: false,
    },
    showLeftArrow: {
      type: Boolean,
      require: false,
      default: false,
    },
    leftText: {
      type: String,
      require: false,
    },
    showRightArrow: {
      type: Boolean,
      require: false,
      default: false,
    },
    rightText: {
      type: String,
      require: false,
    },
  },
  emits: ["click-left", "click-right"],
  setup(props, ctx) {
    const router = useRouter();
    const state = reactive({
      title: "",
      showLeftArrow: true,
      leftText: "",
      showRightArrow: true,
      rightText: "",
    });

    state.title = props.title != null ? props.title : state.title;
    state.showLeftArrow =
      props.showLeftArrow != null ? props.showLeftArrow : state.showLeftArrow;
    state.leftText = props.leftText != null ? props.leftText : state.leftText;
    state.showRightArrow =
      props.showRightArrow != null ? props.showRightArrow : state.showRightArrow;
    state.rightText = props.rightText != null ? props.rightText : state.rightText;

    watch(
      () => props.title,
      (val) => {
        if (val != null) {
          state.title = val;
        }
      }
    );
    watch(
      () => props.showLeftArrow,
      (val) => {
        if (val != null) {
          state.showLeftArrow = val;
        }
      }
    );
    watch(
      () => props.leftText,
      (val) => {
        if (val != null) {
          state.leftText = val;
        }
      }
    );
    watch(
      () => props.showRightArrow,
      (val) => {
        if (val != null) {
          state.showRightArrow = val;
        }
      }
    );
    watch(
      () => props.rightText,
      (val) => {
        if (val != null) {
          state.rightText = val;
        }
      }
    );

    const onClickLeft = () => {
      ctx.emit("click-left");
    };

    const onClickRight = () => {
      ctx.emit("click-right");
    };

    return {
      ...toRefs(state),
      onClickLeft,
      onClickRight,
    };
  },
});
</script>
